package com.ruoyi.ruoyiqywechat.service.aliyun;

//import com.alibaba.nls.client.AccessToken;
import com.alibaba.nls.client.AccessToken;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.qy.oss.OssService;
import com.ruoyi.common.redis.utils.RedisUtil;
import com.ruoyi.ruoyiqywechat.aliyunconfig.SpeechFlashRecognizerDemo;
import com.ruoyi.system.api.RemoteALYService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;

@Service
public class AliyunService {

    @Value("${ALIYUN_AK_ID}")
    private String ALIYUN_AK_ID;
    @Value("${ALIYUN_AK_SECRET}")
    private String ALIYUN_AK_SECRET;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RemoteALYService remoteALYService;

    public String getToken() throws IOException {
        Object o = redisUtil.get(CacheConstants.ALIYUN_MP3_TO_TEXT);
        if(o != null){
            return o.toString();
        }
        AccessToken accessToken = new AccessToken(ALIYUN_AK_ID, ALIYUN_AK_SECRET);
        accessToken.apply();
        String token = accessToken.getToken();
        long expireTime = accessToken.getExpireTime();
        System.out.println("当前阿里云语音转文案的token："+token+"  过期时间："+expireTime);
        redisUtil.set(CacheConstants.ALIYUN_MP3_TO_TEXT,token,8l, TimeUnit.HOURS);//秒
        return token;
    }

    private String pythonScriptPath = "/mnts/jar_work/LiTui/qywechat/index.py"; // Python脚本路径

    public String extractAudioFromVideo(String videoPath, String audioPath) {
        Process process = null;
        try {
            // 使用ProcessBuilder更安全
            ProcessBuilder processBuilder = new ProcessBuilder(
                    "python",
                    pythonScriptPath,
                    videoPath,
                    audioPath
            );

            // 设置工作目录（可选）
            // processBuilder.directory(new File("/path/to/working/directory"));

            // 合并错误流到标准输出
            processBuilder.redirectErrorStream(true);

            // 启动进程
            process = processBuilder.start();

            // 读取输出
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream())
            );

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("Python输出: " + line);

                // 检查成功标志
                if (line.startsWith("SUCCESS:")) {
                    String extractedPath = line.substring(8);
                    int exitCode = process.waitFor();
                    if (exitCode == 0) {
                        System.out.println("输出成功后上传二进制给阿里云录音文件...."+extractedPath);
                        return speechFlashRecognizerDemo.uploadfile(extractedPath,getToken(),"0xZYtJjrqh6klZPm");
                    } else {
                        throw new RuntimeException("Python脚本异常退出，代码: " + exitCode);
                    }
                }
            }

            // 等待进程完成
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("音频提取失败，退出码: " + exitCode);
            }

        } catch (IOException | InterruptedException e) {
            throw new RuntimeException("执行音频提取失败: " + e.getMessage(), e);
        } finally {
            if (process != null) {
                process.destroy();
            }
        }

        throw new RuntimeException("音频提取未返回成功结果");
    }
    @Autowired
    private SpeechFlashRecognizerDemo speechFlashRecognizerDemo;
    public String mp4toText(String audioAddress) {
        System.out.println("音频转文案视频地址："+audioAddress);
        String token = null;
        try {
            token = getToken();
        } catch (IOException e) {
            throw new RuntimeException("阿里云token获取失败");
        }
        try {
//            audioAddress = audioAddress.replace(".mp4", "");
            audioAddress  = OssService.uploadFileVideoFromUrl(audioAddress);
            System.out.println("音频转文案的上传到OSS存储："+audioAddress);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String json = remoteALYService.send("0xZYtJjrqh6klZPm", "mp4", token, audioAddress);
        System.out.println("音频转文案的内容："+json);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            rootNode = mapper.readTree(json);
            JsonNode sentencesNode = rootNode.path("flash_result").path("sentences");
            for (JsonNode sentence : sentencesNode) {
                String text = sentence.path("text").asText();
                stringBuilder.append(text);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException("音频转文案识别不了!");
        }
        return stringBuilder.toString();
    }
}
